<template>
    <el-dialog v-model="visible" title="护理记录" width="90%" :close-on-click-modal="false">
        <!-- 查询区域 -->
        <div class="search-bar">
            <el-form :inline="true" :model="searchForm" class="search-form">
                <el-form-item label="护理记录名称：">
                    <el-input v-model="searchForm.name" placeholder="请输入护理记录名称" clearable />
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="handleSearch">查询</el-button>
                    <el-button @click="handleReset">重置</el-button>
                </el-form-item>
            </el-form>
        </div>

        <!-- 表格区域 -->
        <el-table :data="tableData" v-loading="loading" border style="width: 100%; background: #f5f7fa"
            :header-cell-style="{ background: '#f9fafc', color: '#333', textAlign: 'center' }"
            :cell-style="{ textAlign: 'center' }">
            <el-table-column prop="nursingProject.name" label="护理项目名称" />
            <el-table-column prop="nursingRecord.quantity" label="护理数量" />
            <el-table-column prop="nursingProject.description" label="护理内容" />
            <el-table-column prop="user.username" label="护理人员" />
            <el-table-column prop="user.phone" label="护理人员手机号" />
            <el-table-column label="护理时间">
                <template #default="scope">
                    {{ formatDate(scope.row.nursingRecord.nursingTime) }}
                </template>
            </el-table-column>
            <el-table-column label="操作" min-width="100">
                <template #default="scope">
                    <el-button type="danger" size="small" @click="handleDelete(scope.row)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div class="pagination-bar">
            <el-pagination v-model:current-page="pagination.cur" v-model:page-size="pagination.size"
                :total="pagination.total" :page-sizes="[5, 10, 20]" layout="total, sizes, prev, pager, next, jumper"
                @size-change="handleSizeChange" @current-change="handleCurrentChange" />
        </div>
    </el-dialog>
</template>

<script setup>
import { ref, defineExpose, inject } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'

const axios = inject("axios")

const visible = ref(false)
const clientId = ref(null)
const tableData = ref([])
const loading = ref(false)
const pagination = ref({ cur: 1, size: 5, total: 0 })
const searchForm = ref({ name: '' })

const open = (id) => {
    clientId.value = id
    visible.value = true
    pagination.value.cur = 1
    fetchData()
}

const handleSearch = () => {
    pagination.value.cur = 1
    fetchData()
}

const handleReset = () => {
    searchForm.value.name = ''
    pagination.value.cur = 1
    fetchData()
}

const fetchData = async () => {
    loading.value = true
    try {
        const res = await axios.get('/nursingRecord/pageNursingRecord', {
            params: {
                cur: pagination.value.cur,
                number: pagination.value.size,
                clientId: clientId.value,
                name: searchForm.value.name.trim() || undefined
            }
        })
        if (res.data.status === 200) {
            tableData.value = res.data.data || []
            pagination.value.total = res.data.total || 0
        } else {
            ElMessage.warning(res.data.msg || '获取护理记录失败')
        }
    } catch (e) {
        ElMessage.error('护理记录加载失败')
    } finally {
        loading.value = false
    }
}

const handleCurrentChange = (page) => {
    pagination.value.cur = page
    fetchData()
}

const handleSizeChange = (size) => {
    pagination.value.size = size
    pagination.value.cur = 1
    fetchData()
}

const formatDate = (val) => {
    if (!val) return ''
    const d = new Date(val)
    return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`
}

const handleDelete = (row) => {
    ElMessageBox.confirm(
        `确定删除护理记录「${row.nursingProject.name}」吗？`,
        '警告',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    ).then(async () => {
        try {
            const res = await axios.post(
                '/nursingRecord/deleteNursingRecord',
                null,
                { params: { recordId: row.nursingRecord.recordId } }
            )
            if (res.data.status === 200) {
                ElMessage.success('删除成功')
                fetchData()
            } else {
                ElMessage.warning(res.data.msg || '删除失败')
            }
        } catch (e) {
            ElMessage.error('请求失败')
        }
    }).catch(() => {
        ElMessage.info('取消删除')
    })
}

defineExpose({ open })
</script>

<style scoped>
.search-bar {
    margin: 10px 0;
}

.search-form {
    display: flex;
    align-items: center;
}

.pagination-bar {
    margin-top: 2%;
    margin-bottom: 2%;
    display: flex;
    justify-content: flex-end;
}
</style>
